package com.zlc.common.util;

import com.zlc.common.util.context.ApplicationContextInit;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Desc spring获取bean工具类
 * @author: zl
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Autowired
    private ApplicationContextInit applicationContextInit;

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        if (applicationContext == null) {
            applicationContext = ac;
            applicationContextInit.initContext(ac);
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) throws ClassNotFoundException {
        return getApplicationContext().getBean(name, clazz);
    }

    public static <T>T  getBeanOrName(Class<T> clazz){
        T t = null;
        try {
            t = applicationContext.getBean(clazz);
        }catch (Exception e){
            t = (T) applicationContext.getBean(PlatUtils.lowerFirst(clazz.getSimpleName()));
        }
        return t;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
}
